package com.swkl.yuan.agvtask.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
public class LogController {

    private static final String LOG_FILE_PATH_TEMPLATE = "D:/log/log%d.%i.log";

    @GetMapping("/logs")
    public List<String> getLogs() throws IOException {
        String logFilePath = getCurrentLogFilePath();
        return readLogFile(logFilePath);
    }

    private String getCurrentLogFilePath() throws IOException {
        LocalDate today = LocalDate.now();
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String datePart = today.format(dateFormatter);

        // Replace date placeholder in the file path template
        String logFilePath = LOG_FILE_PATH_TEMPLATE.replace("log%d", "log" + datePart);

        // Find the latest log file by checking the file indices
        for (int i = 0; ; i++) {
            String indexedFilePath = logFilePath.replace("%i", "" + i);
            if (!Files.exists(Paths.get(indexedFilePath))) {
                // Return the previous index as the latest file
                if (i == 0) {
                    throw new IOException("No log files found for today: " + logFilePath);
                }
                return logFilePath.replace("%i", "" + (i - 1));
            }
        }
    }

    private List<String> readLogFile(String logFilePath) throws IOException {
        List<String> logs = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(logFilePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                logs.add(line);
            }
        }
        return logs;
    }
}
